package com.blq.pay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blq.common.core.domain.entity.SysUser;
import com.blq.common.exception.ServiceException;
import com.blq.common.utils.*;
import com.blq.pay.WXConfig;
import com.blq.pay.service.IWxPayService;
import com.blq.system.mapper.SysUserMapper;
import com.blq.system.service.ISysConfigService;
import com.blq.utils.SendOrderMsg;
import com.blq.web.CustomerRepair.domain.CustomerRepair;
import com.blq.web.CustomerRepair.mapper.CustomerRepairMapper;
import com.blq.web.CustomerRepair.service.ICustomerRepairService;
import com.blq.web.PayoutInformation.domain.PayoutInformation;
import com.blq.web.PayoutInformation.mapper.PayoutInformationMapper;
import com.blq.web.domain.UserMoneyItem;
import com.blq.web.mapper.UserMoneyItemMapper;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
@Service
public class WxPayServiceImpl implements IWxPayService {

    private final ISysConfigService sysConfigService;

    private final SysUserMapper sysUserMapper;

    private final CustomerRepairMapper customerRepairMapper;

    private final PayoutInformationMapper payoutInformationMapper;

    private final ICustomerRepairService customerRepairServiceimpl;

    private final UserMoneyItemMapper userMoneyItemMapper;

    SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final String SPBILL_CREATE_IP = "127.0.0.1";
    private static final String TRADE_TYPE_APP = "APP";
    private static final String TRADE_TYPE_NATIVE = "NATIVE";
    private static final String TRADE_TYPE_JSAPI = "JSAPI";

    /**
     * 微信支付订单生成
     *
     * @param moneys     支付金额 带小数点
     * @param type       类型 1app  2 二维码支付  3小程序 公众号支付
     * @param userId     用户id
     * @param outTradeNo 单号
     * @return
     * @throws Exception
     */
    @Override
    public ResultMsg pay(Double moneys, Integer type, String userId, String outTradeNo) throws Exception {
        //h5服务域名配置
        String baseUrl = "https://yn.skuai.net";
        String url;
        if (type == 3) {
            url = baseUrl + "/prod-api/wxPay/notifyJsApi";//小程序支付
        } else if (type == 2) {
            url = baseUrl + "/prod-api/wxPay/notifyMp";//公众号支付
        } else {
            url = baseUrl + "/prod-api/wxPay/notify";//app支付
        }
        String currentTimeMillis = (System.currentTimeMillis() / 1000) + "";
        //后台服务名称
        String appName = "易用能";
        log.info("回调地址：" + url);
        Double mul = AmountCalUtils.mul(moneys, 100);
        String money = String.valueOf(mul.intValue());
        String generateNonceStr = WXPayUtil.generateNonceStr();
        WXConfig config = new WXConfig();
        //微信小程序APPID        微信公众号APPID
        if (type == 1) {
            config.setAppId(sysConfigService.selectConfigByKey("wx.app.appid"));
        } else if (type == 2) {
            config.setAppId(sysConfigService.selectConfigByKey("wx.gzh.appid"));
        } else if (type == 3) {
            config.setAppId(sysConfigService.selectConfigByKey("wx.xcx.appid"));
        }
        //微信商户key
        config.setKey(sysConfigService.selectConfigByKey("wx.sh.key"));
        //微信商户号mchId
        config.setMchId(sysConfigService.selectConfigByKey("wx.shh.mchId"));
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<>();
        //微信对应appid 小程序  公众号  app id
        data.put("appid", config.getAppID());
        //商户号
        data.put("mch_id", config.getMchID());
        //订单号
        data.put("nonce_str", generateNonceStr);
        //订单内容
        data.put("body", appName);
        //生成商户订单号，不可重复
        data.put("out_trade_no", outTradeNo);
        data.put("total_fee", money);
        //自己的服务器IP地址
        data.put("spbill_create_ip", SPBILL_CREATE_IP);
        //异步通知地址（请注意必须是外网）
        data.put("notify_url", url);
        //交易类型
        data.put("trade_type", type == 1 ? TRADE_TYPE_APP : TRADE_TYPE_JSAPI);
        //附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
        data.put("attach", "");
        data.put("sign", WXPayUtil.generateSignature(data, config.getKey(),
                WXPayConstants.SignType.MD5));
        if (type == 3 || type == 2) {
            SysUser sysUser = sysUserMapper.selectById(userId);
            if (type == 2) {
                //公众号openid，暂无
//                data.put("openid", sysUser.getAccountOpenId());
            } else {
                data.put("openid", sysUser.getOpenid());
            }
        }
        //使用官方API请求预付订单
        Map<String, String> response = wxpay.unifiedOrder(data);
        for (String key : response.keySet()) {
            log.info("微信支付订单微信返回参数：keys:" + key + "    value:" + response.get(key).toString());
        }
        if ("SUCCESS".equals(response.get("return_code"))) {//主要返回以下5个参数
            if (type == 1) {
                Map<String, String> param = new HashMap<>();
                param.put("appid", config.getAppID());
                param.put("partnerid", response.get("mch_id"));
                param.put("prepayid", response.get("prepay_id"));
                param.put("package", "Sign=WXPay");
                param.put("noncestr", generateNonceStr);
                param.put("timestamp", currentTimeMillis);
                param.put("sign", WXPayUtil.generateSignature(param, config.getKey(),
                        WXPayConstants.SignType.MD5));
                param.put("outtradeno", outTradeNo);
                return ResultMsg.OBJECT_SUCCESS.setNewData(param);
            } else {
                Map<String, String> param = new HashMap<>();
                param.put("appid", config.getAppID());
                param.put("partnerid", response.get("mch_id"));
                param.put("prepayid", response.get("prepay_id"));
                param.put("noncestr", generateNonceStr);
                param.put("timestamp", currentTimeMillis);
                    /*param.put("sign", WXPayUtil.generateSignature(param, config.getKey(),
                            WXPayConstants.SignType.MD5));*/
                String stringSignTemp = "appId=" + config.getAppID() + "&nonceStr=" + generateNonceStr + "&package=prepay_id=" + response.get("prepay_id") + "&signType=MD5&timeStamp=" + currentTimeMillis + "" + "&key=" + config.getKey();
                String sign = Md5Utils.md5Encrypt32Upper(stringSignTemp).toUpperCase();
                param.put("sign", sign);
                param.put("outtradeno", outTradeNo);
                param.put("package", "prepay_id=" + response.get("prepay_id"));//给前端返回的值
                param.put("mweb_url", response.get("mweb_url"));
                param.put("trade_type", response.get("trade_type"));
                param.put("return_msg", response.get("return_msg"));
                param.put("result_code", response.get("result_code"));
                param.put("signType", "MD5");
                return ResultMsg.OBJECT_SUCCESS.setNewData(param);
            }
        }
        return ResultMsg.OBJECT_ERROR.setNewErrorMsg("获取订单失败");
    }

    /**
     * 接收微信付款结束的回调接口（微信方调用）
     * @param resXml
     * @param payType
     * @return
     */
    @Override
    public String payBack(String resXml, int payType) {
        WXConfig config = null;
        try {
            config = new WXConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.error("进入回调了！！！");
        if (payType == 1) {
            config.setAppId(sysConfigService.selectConfigByKey("wx.app.appid"));
        } else if (payType == 2) {
            config.setAppId(sysConfigService.selectConfigByKey("wx.gzh.appid"));
        } else if (payType == 3) {
            config.setAppId(sysConfigService.selectConfigByKey("wx.xcx.appid"));
        }
        //微信商户key
        config.setKey(sysConfigService.selectConfigByKey("wx.sh.key"));
        //微信商户号mchId
        config.setMchId(sysConfigService.selectConfigByKey("wx.shh.mchId"));
        WXPay wxpay = new WXPay(config);
        String xmlBack = "";
        Map<String, String> notifyMap = null;
        try {
            notifyMap = WXPayUtil.xmlToMap(resXml);         // 调用官方SDK转换成map类型数据
            if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {//验证签名是否有效，有效则进一步处理
                log.error("验证成功！！！");
                String return_code = notifyMap.get("return_code");//状态
                String out_trade_no = notifyMap.get("out_trade_no");//商户订单号
                if (return_code.equals("SUCCESS")) {
                    log.error("验证成功222！！！");
                    if (out_trade_no != null) {
                        // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户的订单状态从退款改成支付成功
                        // 注意特殊情况：微信服务端同样的通知可能会多次发送给商户系统，所以数据持久化之前需要检查是否已经处理过了，处理了直接返回成功标志
                        //业务数据持久化
                        log.error("订单号！！！" + out_trade_no);
                        CustomerRepair customerRepair = customerRepairMapper.selectById(out_trade_no);
                        if (customerRepair != null && "5".equals(customerRepair.getCustomerFlag())) {
                            PayoutInformation payout = payoutInformationMapper.selectOne(new QueryWrapper<PayoutInformation>().eq("customer_key", out_trade_no));
                            if (payout != null && "0".equals(payout.getPaymentStatus())) {
                                String formatdate = time.format(new Date());
                                //系统自动确认收款
                                payoutInformationMapper.updateByOrderId2(out_trade_no, "1", formatdate, formatdate, "1", formatdate, "0");
                            }
                            customerRepair.setCustomerFlag("3");
                            customerRepairMapper.updateById(customerRepair);
                            // 短信提醒
                            SysUser smsUser = sysUserMapper.selectById(customerRepair.getReceiverBy().split(",")[0]);
                            SendOrderMsg.sendDIY("提醒：客户已付款，您有一份<" + customerRepair.getCustomerHelp() + ">订单客户已成功付款，请尽快处理。", smsUser.getPhonenumber());
                            //更新公告信息
                            String content = "提醒：客户已付款，您有一份<" + customerRepair.getCustomerHelp() + ">订单客户已成功付款，请尽快处理。";
                            customerRepairServiceimpl.updateNotice("1", out_trade_no, "备注", content, null, "0", null, null);
                        }
                        System.err.println("微信手机支付回调成功订单号:" + out_trade_no);
                        xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                    } else {
                        System.err.println("微信手机支付回调成功订单号:" + out_trade_no + "");
                        xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                    }
                } else {
                }
                return xmlBack;
            } else {
                // 签名错误，如果数据里没有sign字段，也认为是签名错误
                System.err.println("手机支付回调通知签名错误");
                xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                return xmlBack;
            }
        } catch (Exception e) {
            System.err.println("手机支付回调通知失败" + e);
            xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            log.error("支付回调异常！"+e.getMessage(),e);
        }
        return xmlBack;
    }

    /**
     * 开发测试环境跳过支付直接支付成功
     * @param orderId
     * @return
     */
    @Override
    public String payBackTest(String orderId) {
        CustomerRepair customerRepair = customerRepairMapper.selectById(orderId);
        if (customerRepair != null && "5".equals(customerRepair.getCustomerFlag())) {
            PayoutInformation payout = payoutInformationMapper.selectOne(new QueryWrapper<PayoutInformation>().eq("customer_key", orderId));
            if (payout != null && "0".equals(payout.getPaymentStatus())) {
                String formatdate = time.format(new Date());
                //系统自动确认收款
                payoutInformationMapper.updateByOrderId2(orderId, "1", formatdate, formatdate, "1", formatdate, "0");
            }
            customerRepair.setCustomerFlag("3");
            customerRepairMapper.updateById(customerRepair);
            // 短信提醒
            SysUser smsUser = sysUserMapper.selectById(customerRepair.getReceiverBy().split(",")[0]);
            SendOrderMsg.sendDIY("提醒：客户已付款，您有一份<" + customerRepair.getCustomerHelp() + ">订单客户已成功付款，请尽快处理。", smsUser.getPhonenumber());
            //更新公告信息
            String content = "提醒：客户已付款，您有一份<" + customerRepair.getCustomerHelp() + ">订单客户已成功付款，请尽快处理。";
            customerRepairServiceimpl.updateNotice("1", orderId, "备注", content, null, "0", null, null);
            System.err.println("微信手机支付回调成功订单号:" + orderId + "");
        }
        return "支付成功";
    }

}
